const EosApi = require('eosjs-api')
const mysql = require('mysql');
const moment = require('moment');
const supernode_host = 'https://api.eoslaomao.com';
const bet_logs_constract = 'luckydicelog';


//everything is optional
let options = {
  httpEndpoint: supernode_host, // default, null for cold-storage
  chainId: 'aca376f206b8fc25a6ed44dbdc66547c36c6c33e3a119ffbeaef943642f0e906', // 32 byte (64 char) hex string
  verbose: true, // API logging
  logger: { // Default logging functions
    log: false,
    error:false
  },
  fetchConfiguration: {}
}

var pool  = mysql.createPool({
    connectionLimit : 10,
    host            : '127.0.0.1',
    port            : '3334',
    user            : 'root',
    password        : '5K*csy+}PSu%kMB',
    database        : 'dev_onedice_io'
});

//moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
function insertBetHistory(values) {
    if(values.length == 0 ) {
        console.log("can't insert to mysql , values's length = 0 ");
        return;
    }
    console.log("datas to be insert into db :"+JSON.stringify(values));
    // var value1 = [
    //       ["2018-10-17T13:18:41.500","eosdice55555","0.1000",50,70,"0.0000",35,"a152b22c8d1c685e2da65da8732d70801017cb5e008be89ec31c76e3588084e7"]
    //     ];
    pool.getConnection(function(err, connection) {
        if (err) throw err; // not connected!
        console.log("MySql Connected!");
        // Use the connection
        var sql = " INSERT IGNORE  INTO bets(`time`,`username`,`bet`, `roll_under`,`roll`,`payout`,`sn`,`tx_id`) VALUES ?";
        connection.query(sql,[values], function (error, results, fields) {
          // When done with the connection, release it.
          connection.release();
          // Handle error after the release.
          if (error) {
            console.error("mysql error :"+JSON.stringify(error));
            throw error;
          }
          console.log("MySql insertBetHistory success !");
          // Don't use the connection here, it has been returned to the pool.
        });
    });
}

api = EosApi(options)

function readHistory() {
    api.getActions(bet_logs_constract, -1, -20).then(({ actions }) => {

      let datas = actions.filter(action => {
          return action.action_trace
            && action.action_trace.act
            && action.action_trace.act.data
            && action.action_trace.act.data.result 
            && action.action_trace.act.data.result.bet_id;//保证是一个合法的交易记录
      }).reverse();

      let results = datas.map(function(data,index,array){
          /**
            * {
          "bet_id":21,
          "player":"himoutoumaru",
          "referrer":"luckydicewin",
          "amount":"0.1000 EOS",
          "roll_under":50,
          "random_roll":89,
          "seed":"a716f763f6e74c1fdd59fcf0f591db17b751b6e7d3d70d0e5ec487225049d74d",
          "seed_hash":"304f32bad7186ab058fb8d125dfd6ebda028bd5a45cd28777bb44dbcd2318c49",
          "user_seed_hash":"fd953dd748871a183599ba071b16f0b2643c80ac",
          "payout":"0.0000 EOS"
          },
            */
          //`time`,`username`,`bet`, `roll_under`,`roll`,`payout`
          return  [
              data.action_trace.block_time,
              data.action_trace.act.data.result.player,
              data.action_trace.act.data.result.amount.split(" ")[0],
              data.action_trace.act.data.result.roll_under,
              data.action_trace.act.data.result.random_roll,
              data.action_trace.act.data.result.payout.split(" ")[0],
              data.action_trace.act.data.result.bet_id,//游戏全局ID，递增
              data.action_trace.trx_id,
          ];//data.action_trace.act.data.result;
      });
      //console.error(results);
      insertBetHistory(results)
    }).catch((err) => {
        console.log(JSON.stringify(err));
    });
}

setInterval(readHistory,3000);
